package wahadlo.gui;

import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.util.HashMap;
import java.util.Map;

import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JTextField;

import wahadlo.model.Model;
import wahadlo.model.ModelSupplier;

/**
 * Klasa reprezentuje pole tekstowe z opisem.
 * 
 * @author Koziołek
 * 
 */
class SimpleDataPanel extends JComponent implements ModelSupplier {
	private static final long serialVersionUID = 1L;
	private String title;
	private String unitName;
	private JTextField textField;
	private JLabel titleLabel;

	/**
	 * 
	 * @param title
	 *            nazwa pola
	 * @param unitName
	 *            jednostki
	 */
	public SimpleDataPanel(String title, String unitName) {
		this(title, unitName, "");
	}

	/**
	 * 
	 * @param title
	 *            nazwa pola
	 * @param unitName
	 *            jednostki
	 * @param defaultValue
	 *            wartość domyślna
	 */
	public SimpleDataPanel(String title, String unitName, String defaultValue) {
		this.title = title;
		this.unitName = unitName;
		init();
		textField.setText(defaultValue);
	}

	private void init() {
		titleLabel = new JLabel(title + "[" + unitName + "]");
		textField = new JTextField();
		GridLayout layout = new GridLayout(2, 1);
		setLayout(layout);
		textField.addKeyListener(new KeyAdapter() {
			public void keyTyped(KeyEvent e) {
				if (e.getKeyChar() == '.'
						&& textField.getText().indexOf('.') > -1) {
					e.consume();
					return;
				}
				if (e.getKeyChar() == '-'
						&& textField.getText().indexOf('-') > -1) {
					e.consume();
					return;
				}
				if (!((e.getKeyChar() >= '0' && e.getKeyChar() <= '9')
						|| e.getKeyChar() == '.' || e.getKeyChar() == '-'))
					e.consume();
			}
		});

		add(titleLabel, 0);
		add(textField, 1);

	}

	/* (non-Javadoc)
	 * @see wahadlo.model.ModelSupplier#getModel()
	 */
	public Model getModel() {
		return new Model() {

			public Map<Object, Object> getProperties() {
				Map<Object, Object> model = new HashMap<Object, Object>();
				if (textField.getText().trim().length() > 0)
					model.put("value", Double.parseDouble(textField.getText()));
				return model;
			}
		};
	}

	@Override
	public Dimension getPreferredSize() {
		return super.getPreferredSize();
	}

}
